<template>
  <div class="tenant-edit-container">
    <div class="edit-form-container">
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="rules" 
        label-width="220px" 
        class="demo-form"
      >
        <!-- 系统链接 -->
        <el-form-item label="系统链接" prop="tags">
          <el-select
            v-model="formData.tags"
            multiple
            disabled
            placeholder="从租户管理获取的数据"
            style="width: 100%"
          >
            <el-option
              v-for="item in systemLinks"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <div class="form-tips">此字段为只读，数据来源于租户管理</div>
        </el-form-item>

        <!-- 超级管理员用户名 -->
        <el-form-item label="超级管理员用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名（英文/数字）"
            maxlength="20"
            show-word-limit
            @blur="validateUsernameUnique"
          />
        </el-form-item>

        <!-- 超级管理员密码 -->
        <el-form-item label="超级管理员密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            maxlength="20"
            show-word-limit
            show-password
          />
        </el-form-item>

        <!-- 公司名称 -->
        <el-form-item label="公司名称" prop="company">
          <el-input
            v-model="formData.company"
            placeholder="请输入公司名称（中文/英文/数字）"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <!-- 企业logo -->
        <el-form-item label="企业logo" prop="avatar">
          <div class="upload-area">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload"
            >
              <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
              <div v-else class="avatar-uploader-icon">
                <i class="el-icon-plus"></i>
                <div>点击上传logo</div>
              </div>
            </el-upload>
            <div class="upload-tips">
              <p>支持格式：jpg、jpeg、png、webp</p>
              <p>建议尺寸：200×200像素</p>
              <p>最大大小：2MB</p>
            </div>
          </div>
        </el-form-item>

        <!-- UI配置文件 -->
        <el-form-item label="UI配置文件" prop="file">
          <div class="file-upload-area">
            <el-upload
              class="file-uploader"
              action="#"
              :before-upload="beforeFileUpload"
              :http-request="handleFileUpload"
            >
              <el-button size="small" type="primary">
                <i class="el-icon-upload"></i> 点击上传配置文件
              </el-button>
            </el-upload>
            <div v-if="formData.file" class="file-info">
              <i class="el-icon-document"></i>
              <span>{{ formData.file }}</span>
              <el-button type="text" @click="removeFile">删除</el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitForm" :loading="loading">
            {{ loading ? '提交中...' : '保存配置' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type UploadRequestOptions } from 'element-plus'
import type { FormRules } from 'element-plus'
import { userApi } from '@/api/user'
import { fileApi } from '@/api/file'

// 类型定义
interface SystemLink {
  label: string
  value: string
}


interface FormData {
  tags: string[]
  username: string
  password: string
  company: string
  avatar: string
  file: string
}

// 响应式数据
const loading = ref(false)
const formRef = ref<FormInstance>()
const usernameChecking = ref(false)

const formData = reactive<FormData>({
  tags: [],
  username: '',
  password: '',
  company: '',
  avatar: '',
  file: '',
})

const systemLinks: SystemLink[] = [
  { label: '系统管理后台', value: 'admin' },
  { label: '用户中心', value: 'user' },
  { label: 'API接口', value: 'api' }
]

// 验证规则
const validateUsername = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入用户名'))
  } else if (!/^[a-zA-Z0-9]+$/.test(value)) {
    callback(new Error('用户名只能包含英文和数字'))
  } else if (value.length > 20) {
    callback(new Error('用户名不能超过20个字符'))
  } else {
    callback()
  }
  console.log(rule)
}

const validatePassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length > 20) {
    callback(new Error('密码不能超过20个字符'))
  } else {
    callback()
  }
  console.log(rule)
}

const validateCompany = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入公司名称'))
  } else if (!/^[\u4e00-\u9fa5a-zA-Z0-9]+$/.test(value)) {
    callback(new Error('公司名称只能包含中文、英文和数字'))
  } else if (value.length > 50) {
    callback(new Error('公司名称不能超过50个字符'))
  } else {
    callback()
  }
  console.log(rule)
}

const rules: FormRules = {
  username: [
    { required: true, validator: validateUsername, trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  company: [
    { required: true, validator: validateCompany, trigger: 'blur' }
  ]
}

// 方法
const loadTenantData = async (): Promise<void> => {
  try {
    // 模拟API调用
    const result = await userApi.getUserInfo()

    // const mockData = {
    //   tags: ['admin', 'user'],
    //   username: 'admin123',
    //   password: 'password123',
    //   company: '示例公司',
    //   avatar: '',
    //   file: null
    // }
    Object.assign(formData, result.data)
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
}

const checkUsernameUnique = async (username: string): Promise<boolean> => {
  try {
    // 模拟API调用
    // const response = await api.checkUsername({ username })
    await new Promise(resolve => setTimeout(resolve, 500)) // 模拟网络延迟
    // 假设用户名为 'admin' 的已存在
    return username !== 'admin'
  } catch (error) {
    ElMessage.error('检查用户名失败')
    return false
  }
}

const validateUsernameUnique = async (): Promise<void> => {
  if (!formData.username || formData.username.length === 0) return

  usernameChecking.value = true
  const isUnique = await checkUsernameUnique(formData.username)
  usernameChecking.value = false

  if (!isUnique) {
    ElMessage.error('用户名已存在，请更换其他用户名')
    formData.username = ''
  }
}

const beforeAvatarUpload = (file: File): boolean => {
  const isImage = /\.(jpg|jpeg|png|webp)$/i.test(file.name)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传jpg、jpeg、png、webp格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarUpload = async (options: UploadRequestOptions): Promise<void> => {
  try {
    loading.value = true
    const response = await fileApi.upload(options.file)
    const url = response.data.url

    // 正确地更新响应式数据
    formData.avatar = url
    ElMessage.success('头像上传成功')
  } catch (error) {
    ElMessage.error('头像上传失败')
  } finally {
    loading.value = false
  }
}

const beforeFileUpload = (file: File): boolean => {
  const isConfigFile = /\.(json|txt|xls|xlsx|doc|pdf|png|jpg|jpeg|gif|yml|yaml|config|xml)$/i.test(file.name)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isConfigFile) {
    ElMessage.error('只能上传配置文件格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过 5MB!')
    return false
  }
  return true
}

const handleFileUpload = async (options: UploadRequestOptions): Promise<void> => {
  try {
    loading.value = true
    const response = await fileApi.upload(options.file)
    const url = response.data.url
    // 正确地更新响应式数据
    formData.file = url
    ElMessage.success('配置文件上传成功')
  } catch (error) {
    ElMessage.error('配置文件上传失败')
  } finally {
    loading.value = false
  }
}

const removeFile = (): void => {
  formData.file = ''
}

const submitForm = async (): Promise<void> => {
  if (!formRef.value) return
  console.log(formData)
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true
    
    await userApi.editUserInfo(formData)
    
    ElMessage.success('配置保存成功')
  } catch (error) {
    ElMessage.error('保存失败，请检查表单')
  } finally {
    loading.value = false
  }
}

const resetForm = (): void => {
  if (!formRef.value) return
  formRef.value.resetFields()
  formData.avatar = ''
  formData.file = ''
}

const cancelEdit = (): void => {
  ElMessageBox.confirm('确定要取消编辑吗？未保存的更改将会丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 在实际项目中，这里应该是路由返回
    // router.back()
    ElMessage.info('已取消编辑')
  })
}

// 生命周期
onMounted(() => {
  loadTenantData()
})
</script>

<style scoped>
.tenant-edit-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.edit-form-container {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.demo-form {
  max-width: 600px;
}

.form-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.upload-area {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #8c939d;
  font-size: 14px;
}

.avatar-uploader-icon i {
  font-size: 28px;
  margin-bottom: 8px;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tips {
  flex: 1;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

.file-upload-area {
  width: 100%;
}

.file-info {
  margin-top: 8px;
  padding: 8px 12px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-info i {
  color: #409eff;
}

.form-actions {
  margin-top: 32px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tenant-edit-container {
    padding: 12px;
  }
  
  .edit-form-container {
    padding: 16px;
  }
  
  .upload-area {
    flex-direction: column;
    gap: 12px;
  }
  
  .upload-tips {
    margin-left: 0;
  }
}
</style>